<template>
  <div class="q-pa-sm">
    <create-user ref="userAdd" createNew @refresh="getAll" />
    <authority-allocation ref="authority" @refresh="getAll" />
    <q-splitter
      class="orientation-landscape full-height"
      v-model="splitterModel"
      separator-class="bg-grey-8"
    >
      <!--  用户信息    -->
      <template v-slot:before>
        <q-table
          :rows="userList"
          :columns="columns"
          row-key="name"
          class="full-height q-mr-sm"
          :title="$t(lang + 'text1')"
        >
          <template v-slot:top-right>
            <q-btn
              no-caps
              icon="add"
              outline
              color="primary"
              :label="$t(lang + 'text2')"
              @click="userAdd.show()"
            />
          </template>
          <template v-slot:body-cell-role="props">
            <q-td class="text-center">
              <q-select
                :options="userOptions"
                v-model="props.row.role"
                dense
                outlined
                map-options
                emit-value
                @update:model-value="updateRole(props.row)"
              />
            </q-td>
          </template>
          <template v-slot:body-cell-operate="props">
            <q-td class="text-center q-gutter-x-sm">
              <q-btn
                no-caps
                outline
                color="secondary"
                :label="$t(lang + 'text3')"
                @click="authority.show(props.row)"
              />
              <q-btn
                no-caps
                outline
                color="secondary"
                :label="$t(lang + 'text4')"
                @click="changePassword(props.row)"
              />
              <q-btn
                no-caps
                outline
                :label="$t(lang + 'text5')"
                color="red"
                @click="remove(props.row)"
              />
            </q-td>
          </template>
        </q-table>
      </template>
      <!--  授权表格    -->
      <template v-slot:after>
        <q-table
          :rows="noAccreditList"
          :columns="columns"
          row-key="name"
          class="full-height q-ml-sm"
          :title="$t(lang + 'text6')"
          v-if="noAccreditList.length"
        >
          <template v-slot:body-cell-operate="props">
            <q-td class="text-center q-gutter-x-sm">
              <q-btn
                :label="$t(lang + 'text7')"
                color="negative"
                :size="$q.screen.lt.md ? 'sm' : 'md'"
                outline
                @click="refuse(props.row)"
              />
              <q-btn
                :label="$t(lang + 'text8')"
                color="positive"
                :size="$q.screen.lt.md ? 'sm' : 'md'"
                outline
                @click="accept(props.row)"
              />
            </q-td>
          </template>
        </q-table>
        <div
          class="absolute-center text-h5 text-grey"
          style="white-space: nowrap"
          v-else
        >
          {{ $t(lang + "text9") }}
        </div>
      </template>
    </q-splitter>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import { useAPIStore } from "stores/api";
import CreateUser from "components/user/CreateUser.vue";
import { useQuasar } from "quasar";
import AuthorityAllocation from "pages/user/AuthorityAllocation.vue";
import { useUiStore } from "stores/ui";
import { useI18n } from "vue-i18n";
import { userApi } from "boot/axios";

const t = useI18n().t;
const lang = "userIndex.UserManage.";
const $q = useQuasar();
const ui = useUiStore();
// 权限选择
const options = { user: t(lang + "text10"), admin: t(lang + "text11") };
const userOptions = [
  { label: t(lang + "text10"), value: "user" },
  { label: t(lang + "text11"), value: "admin" },
];

// 表头信息 format操作显示文字 不影响实体
const columns = [
  {
    name: "username",
    align: "center",
    label: t(lang + "text12"),
    field: "username",
  },
  {
    name: "role",
    align: "center",
    label: t(lang + "text13"),
    field: "role",
    format: (val) => `${options[val]}`,
  },
  {
    name: "operate",
    align: "center",
    label: t(lang + "text14"),
    field: "operate",
  },
];
// 左右平均分割页面大小
const splitterModel = ref(70);
// 用户信息
const userList = ref([]);
// 未授权的用户信息
const noAccreditList = ref([]);
// 创建用户
const userAdd = ref();
// 权限模块修改
const authority = ref();

// 测试登录
onMounted(() => {
  getAll();
});

// 获取用户所有信息
function getAll() {
  userApi.get(useAPIStore().centerUrl + "user/list").then((res) => {
    if (res.data) {
      userList.value = res.data.filter(
        (item) => item.role !== "root" && item.authorize === true
      );
      // 拿出未授权信息
      if (res.data.length !== 0) {
        noAccreditList.value = res.data.filter(
          (item) => item.authorize === false && item.role !== "root"
        );
      }
    }
  });
}
// 拒绝授权
function refuse(data) {
  $q.dialog({
    title: t(lang + "text7") + data.username + t(lang + "text15"),
    message: t(lang + "text16"),
    cancel: t("cancel"),
    ok: t("ok"),
    dark: ui.isDark,
    persistent: true,
  }).onOk(() => {
    userApi.delete(useAPIStore().centerUrl + "user/" + data.id).then((res) => {
      if (res.data === "done") {
        $q.notify({ type: "positive", message: t(lang + "text17") });
        getAll();
      } else {
        $q.notify({ type: "warning", message: t(lang + "text18") });
      }
    });
  });
}
// 批准用户
function accept(data) {
  const params = {
    target: data.id,
    authorize: true,
  };
  userApi
    .get(useAPIStore().centerUrl + "user/modify/authorize", { params })
    .then((res) => {
      if (res.data === "done") {
        $q.notify({ type: "positive", message: t(lang + "text19") });
        getAll();
      } else {
        $q.notify({ type: "warning", message: t(lang + "text18") });
      }
    })
    .catch(() => {
      $q.notify({ type: "warning", message: t("requestTimeout") });
    });
}
// 修改密码 （后端非空未判断）
function changePassword(data) {
  $q.dialog({
    title: t(lang + "text20") + data.username + t(lang + "text21"),
    message: t(lang + "text22"),
    prompt: {
      model: "",
      type: "text",
    },
    cancel: t("cancel"),
    ok: t("ok"),
    dark: ui.isDark,
    persistent: false,
  }).onOk((pwd) => {
    if (!pwd)
      return $q.notify({ type: "warning", message: t(lang + "text23") });
    const param = {
      id: data.id,
      newRepeat: pwd,
      new: pwd,
    };
    userApi
      .get(useAPIStore().centerUrl + "user/modify/others/password", {
        params: param,
      })
      .then((res) => {
        if (res.data === "done") {
          $q.notify({ type: "positive", message: t(lang + "text24") });
        } else {
          $q.notify({ type: "warning", message: res.data });
        }
      });
  });
}
// 修改用户权限 （需要操作人的id和密码不合适）
function updateRole(data) {
  const params = {
    id: "9b8ce62f-f5b9-4984-8137-7d1ba26d06fd",
    password: "sagetech",
    target: data.id,
    role: data.role,
  };
  userApi
    .get(useAPIStore().centerUrl + "user/modify/role", { params })
    .then((res) => {
      if (res.data === "done") {
        $q.notify({ type: "positive", message: t(lang + "text25") });
      } else {
        $q.notify({ type: "warning", message: t(lang + "text26") });
      }
    })
    .catch(() => {
      $q.notify({ type: "warning", message: t("requestTimeout") });
    });
}
// 注销用户
function remove(data) {
  $q.dialog({
    title: t(lang + "text5") + data.username + t(lang + "text15"),
    message: t(lang + "text27"),
    cancel: t("cancel"),
    ok: t("ok"),
    dark: ui.isDark,
    persistent: true,
  }).onOk(() => {
    userApi.delete(useAPIStore().centerUrl + "user/" + data.id).then((res) => {
      if (res.data === "done") {
        getAll();
        $q.notify({ message: t(lang + "text28"), type: "positive" });
      } else {
        $q.notify({ type: "warning", message: t(lang + "text18") });
      }
    });
  });
}
</script>
